package com.motu.monstercity.server.gate;

import com.motu.monstercity.module.common.redis.RedisKey;
import com.motu.monstercity.module.common.utility.EventBusConstant;
import com.motu.vertx.module.utility.redis.RedisTools;
import com.motu.vertx.module.utility.toolset.Tool;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.Promise;
import io.vertx.core.eventbus.EventBus;
import io.vertx.core.eventbus.MessageConsumer;
import io.vertx.core.http.ServerWebSocket;
import io.vertx.core.json.JsonObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;

/**
 * player_online数据更新
 *
 * @author 黄贤玮
 * create date: 2023/7/31
 */
public class GateMonitor2Verticle extends AbstractVerticle {

    public final static Logger logger = LoggerFactory.getLogger(GateMonitor2Verticle.class);

    @Override
    public void start(Promise<Void> future) throws Exception {
        EventBus eb = vertx.eventBus();

        String ebName = EventBusConstant.getAddress(EventBusConstant.MONITOR_SAVEDATA_PLAYERONLINE);
        MessageConsumer<JsonObject> consumer = eb.consumer(ebName);
        logger.info("---===#*#*#*#===---* gate start ebName:" + ebName);

        consumer.handler(message -> {
            //--------更新player_online数据--------
            JsonObject recData = message.body();
            int time = recData.getInteger("time");
            ConcurrentHashMap<Long, ServerWebSocket> conMap = SocketManager.getSocketList();
            logger.info("---===#*#*#*#===---* gate receive notice save play_online time:" + time + " conMap.size = " + conMap.size());
            // 统计在线数据
            ConcurrentHashMap<Integer, Integer> onlineMap = new ConcurrentHashMap<>();
            for (Entry<Long, ServerWebSocket> entry : conMap.entrySet()) {
                int sid = SocketInfo.getServerId(entry.getValue());
                int count = 1;
                if (onlineMap.containsKey(sid)) {
                    count += onlineMap.get(sid);
                }
                onlineMap.put(sid, count);
            }

            // 更新到redis
            String playerOnlineKey = RedisKey.getMonitorPlayerOnlineKey(time);
            for (Entry<Integer, Integer> entry : onlineMap.entrySet()) {
                int num = entry.getValue();
                if (num > 0) {
                    RedisTools.addHashField(playerOnlineKey, entry.getKey().toString(), num);
                }
            }
            // 一分钟后才会使用里面的数据，设置个过期
            RedisTools.expire(playerOnlineKey, Tool.MINUTE * 15);

        });

        consumer.completionHandler(res2 -> {
            if (res2.succeeded()) {
                future.complete();
                logger.info("The Save(player_online)Verticle handler registration has reached all nodes");
            } else {
                future.fail("Save(player_online)Verticle handler registration failed! " + res2.cause().toString());
                logger.error("Save(player_online)Verticle Registration failed! " + res2.cause().toString());
            }
        });

    }

}
